#include "main.h"
#include <stdio.h>
#include <string.h>
#include "driver_led_key.h"
#include "driver_dbg.h"
#include "driver_net.h"
void MySystemClock_Config(void);

int main(void)
{
	int DataLen = 0;
	uint8_t buf[128] = {0};
	KeyEvent nKeyEvent = {0};
	HAL_Init();
	MySystemClock_Config();

	Driver_LED_Init();
	Driver_Key_Init();
	Driver_DBG_Init();
	
	Driver_Net_Init();
	
	printf("hello world\r\n");
	
	if(0 == Driver_Net_ConnectWiFi("ota", "12345678", 5000))
	{
		printf("connect WiFi successed.\r\n");
	}
	else
	{
		printf("connect WiFi failed.\r\n");
	}
	if(Driver_Net_ConnectTcp("192.168.3.19", 8989, 1000) == 0)
	{
		printf("Connect TCP success.\r\n");
	}
	else
	{
		printf("Connect TCP failed.\r\n");
	}
	Driver_Net_TransmitSocket("Hello world", 11, 500);
	while(1)
	{
		if(Driver_Key_Read((uint8_t*)&nKeyEvent.cmd, sizeof(KeyEvent)) == 0)
		{
			LED_SHINE();
			Driver_Net_TransmitSocket("press key", 9, 500);
			printf("Key has been pressed, cmd = %d, time = %d\r\n", nKeyEvent.cmd, nKeyEvent.time);
		}
		if((DataLen = Driver_Net_RecvSocket((char*)buf, 128, 1000)) > 0)
		{
			printf("Receive socket: Len = %d, %s\r\n",DataLen, buf);
			for(int i = 0; i < DataLen;  i++) printf("%02X ", buf[i]);
			printf("\r\n");
			memset(buf, 0, sizeof(buf));
		}
		HAL_Delay(1000);
	}
}

void MySystemClock_Config(void)
{
	RCC_OscInitTypeDef  RCC_OscInitStruct;
	RCC_ClkInitTypeDef  RCC_ClkInitStruct;
	
	RCC_OscInitStruct.OscillatorType 	= RCC_OSCILLATORTYPE_HSE;
	RCC_OscInitStruct.HSEState			= RCC_HSE_ON;
	RCC_OscInitStruct.HSEPredivValue    = RCC_HSE_PREDIV_DIV1;
	RCC_OscInitStruct.HSIState			= RCC_HSI_OFF;
	RCC_OscInitStruct.PLL.PLLState		= RCC_PLL_ON;
	RCC_OscInitStruct.PLL.PLLSource		= RCC_PLLSOURCE_HSE;
	RCC_OscInitStruct.PLL.PLLMUL		= RCC_PLL_MUL9;
	
	HAL_RCC_OscConfig(&RCC_OscInitStruct);
	
	RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK
								| RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
	RCC_ClkInitStruct.SYSCLKSource 		= RCC_SYSCLKSOURCE_PLLCLK;
	RCC_ClkInitStruct.AHBCLKDivider 	= RCC_SYSCLK_DIV1;
	RCC_ClkInitStruct.APB1CLKDivider  	= RCC_HCLK_DIV2;
	RCC_ClkInitStruct.APB2CLKDivider  	= RCC_HCLK_DIV1;
	
	HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2);
}
